<template>
  <div class="p-b-80" v-if="ready">
    <van-nav-bar
      class="bg-red text-white"
      :title="`${isEdit ? '编辑' : '添加'}商品`"
      @click-left="$router.go(-1)"
      left-arrow
    ></van-nav-bar>
    <div class="p-b-10">
      <van-field
        required
        v-model="goods.title"
        :error-message="rule.title"
        placeholder="标题 品类品牌都是买家喜欢搜索的"
      />
      <van-field
        required
        v-model="goods.desc"
        type="textarea"
        placeholder="商品描述"
        rows="4"
        autosize
        :error-message="rule.desc"
      />
      <p
        class="text-right m-t-10 m-r-10 text-grey fs-12"
        :class="{'text-red': rule.desc}"
      >{{goods.desc.length}} / 150</p>
      <div>
        <div v-if="editImg" class="w-80 h-80 o-hidden m-l-15 relative">
          <img class="w-full" :src="goods.uploadImgs[0]" />
          <van-icon
            @click="handleDelImg()"
            class="absolute bottom-5 right-0 z-index-3 text-content bg-white"
            name="delete"
          />
        </div>
        <van-uploader
          v-else
          class="m-l-15"
          v-model="goods.uploadImgs"
          multiple
          upload-text="添加图片"
          :before-read="beforeRead"
          :max-size="uploadImgsMaxSize"
          @oversize="handleOversize"
          :max-count="1"
        />
      </div>
    </div>
    <div class="b-t b-t-w-15">
      <van-cell-group>
        <van-field
          class="flex a-center"
          v-model="goods.price"
          type="number"
          clearable
          label="门市价"
          placeholder="¥0.0"
        />
        <van-field
          required
          class="flex a-center"
          type="number"
          v-model="goods.discounts"
          label="优惠量"
          :placeholder="goods.discountsType === 1 ? '0-100, 10 = 1.0折' : '2'"
          :error-message="rule.discounts"
        >
          <div slot="button">
            <span class="m-r-10">{{goods.discountsType === 1 ? '折' : '元'}}</span>
            <van-button
              @click="goods.discountsType = 1"
              size="mini"
              :class="{'bg-red text-white': goods.discountsType === 1}"
              class="bg-grey b-none b-r-r-0"
            >折扣</van-button>
            <van-button
              @click="goods.discountsType = 2"
              size="mini"
              :class="{'bg-red text-white': goods.discountsType === 2}"
              class="bg-grey b-l-r-0 b-none m-l--5"
            >现金</van-button>
          </div>
        </van-field>
        <van-field
          required
          class="flex a-center"
          v-model="featureTxt"
          type="text"
          label="商品特征"
          placeholder="5个字以内, 最多可添加5个"
          :error-message="rule.feature"
        >
          <div slot="button">
            <van-button @click="handleAddFeature()" size="mini" plain type="warning">添加</van-button>
          </div>
        </van-field>
        <div v-if="goods.feature.length" class="p-10 p-h-15">
          <van-button
            v-for="item in goods.feature"
            :key="item"
            size="small"
            class="m-r-10 m-b-5"
            type="default"
            @click="handleDelFeature(item)"
          >
            <p class="flex a-center">
              <span>{{item}}</span>
              <van-icon name="cross" class="p-h-5" />
            </p>
          </van-button>
        </div>
        <van-field
          required
          class="flex a-center"
          v-model="goods.unit"
          type="text"
          label="商品单位"
          placeholder="个 / 件 / 瓶 /..."
          :error-message="rule.unit"
        />
        <van-field
          required
          class="flex a-center"
          v-model="goods.residue"
          type="number"
          label="每日库存量"
          placeholder="每日可消费数量"
          :error-message="rule.residue"
        />
        <van-field
          required
          class="flex a-center"
          v-model="goods.limit"
          type="number"
          label="日消费限额"
          placeholder="每人每天可消费次数"
          :error-message="rule.limit"
        />
        <van-cell title="单元格" class="required">
          <template slot="title">
            <div class="flex">
              <p class="w-90">商品类型</p>
              <select v-model="goods.type" class="w-full fs-13 text-content m-l-15 select">
                <option disabled value>请选择商品分类</option>
                <option v-for="(item, index) in types" :key="index">{{item}}</option>
              </select>
            </div>
          </template>
        </van-cell>
        <van-radio-group v-model="goods.method" class="flex p-15">
          <van-radio :name="1">预约</van-radio>
          <van-radio :name="2" class="m-l-20">到店</van-radio>
        </van-radio-group>
      </van-cell-group>
    </div>
    <div class="fixed bottom-0 w-full p-10 bg-white">
      <van-button
        @click="handleSubmit()"
        class="w-full"
        type="danger"
      >{{`${isEdit ? '确认修改' : '确认发布'}`}}</van-button>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  data () {
    return {
      ready: false,
      isEdit: false,
      goods: {
        title: '', // 40个字
        desc: '', // 150个字
        uploadImgs: [],
        price: null, //
        discounts: null,
        feature: [],
        unit: '',
        residue: null,
        limit: null,
        method: 1,
        discountsType: 1,
        type: ''
      },
      rule: {
        title: '', // 40个字
        desc: '', // 150个字
        discounts: '',
        feature: '',
        residue: '',
        limit: ''
      },
      uploadImgsMaxSize: 2000000,
      featureTxt: '',
      types: [],
      editImg: null
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    async init () {
      await this.getTypes()
      if (this.$route.query.id) {
        this.isEdit = true
        this.editImg = true
        await this.getDetail()
      }
      this.ready = true
    },
    async getDetail () {
      let { id } = this.$route.query
      if (!id) this.$router.push('/')
      let { status, zxGd } = await this.$api.post('/zxGd/queryById', {
        id
      })
      if (status === 0) {
        zxGd.sptz = zxGd.sptz.split(',').filter(d => d !== '')
        console.log(zxGd)
        this.goods.title = zxGd.gname
        this.goods.desc = zxGd.spms
        this.goods.uploadImgs = [zxGd.picture]
        this.goods.price = zxGd.fprice
        this.goods.discountsType = zxGd.yhtype === 1 ? 1 : 2
        this.goods.discounts = zxGd.zk
        this.goods.feature = zxGd.sptz
        this.goods.unit = zxGd.unit
        this.goods.residue = zxGd.yye
        this.goods.limit = zxGd.rxe
        this.goods.method = zxGd.method
        this.goods.type = zxGd.gtype
        console.log(this.goods)
      }
    },
    handleDelImg () {
      this.goods.uploadImgs = []
      this.editImg = false
    },
    handleOversize (file, name) {
      this.$toast.fail(`大小超过${this.uploadImgsMaxSize / 1000000}M`)
    },
    async getTypes () {
      let { status, zxBsGtList } = await this.$api.post('/bsGt/query', {
        bid: this.user.userInfo.id
      })
      if (status === 401) return
      this.types = zxBsGtList.map(d => d.gtype)
    },
    async handleSubmit () {
      if (this.isValid()) {
        let loading = this.$toast.loading({
          mask: true,
          message: '正在提交...',
          duration: 0
        })
        // 拿到图片地址
        let imgUrl = []
        let imgs = await this.uploadImg()
        for (const item of imgs) {
          if (item.status === 0) {
            imgUrl.push(item.url)
          } else {
            this.$toast.fail('item.message')
            return
          }
        }
        // 将url数组转字符串
        imgUrl = imgUrl.join(',')
        let { title, desc, price, discounts, feature,
          residue, limit, method, discountsType, type, unit } = this.goods
        let submitData = {
          gname: title,
          spms: desc,
          gtype: type,
          sptz: feature,
          picture: imgUrl,
          zk: discounts,
          unit: unit,
          yye: residue,
          rxe: limit,
          method,
          yhtype: discountsType,
          fprice: price
        }
        // 发布商品
        let { status, message } = await this.$api.post('/zxGd/add', submitData)
        loading.clear()
        if (status === 0) {
          this.$dialog.alert({
            title: '提示',
            message,
            confirmButtonColor: '#fd4f51'
          }).then(() => {
            this.$router.push('/')
          })
        } else {
          this.$toast.fail(message)
        }
      } else {
        this.$toast('请完善商品信息')
      }
    },
    async uploadImg () {
      let promises = this.goods.uploadImgs.map(async item => {
        let formData = new FormData()
        formData.append('file', item.file)
        let res = await this.$api.postFile('/uploadFile', formData)
        return res
      })
      let allResult = await Promise.all(promises)
      return allResult
    },
    isValid () {
      if (this.goods.title.length > 0 && this.goods.desc.length > 0 &&
        `${this.goods.discounts}`.length > 0 && this.goods.feature.length > 0 &&
        this.goods.unit.length > 0 && this.goods.uploadImgs.length > 0 &&
        `${this.goods.residue}`.length > 0 && `${this.goods.limit}`.length > 0 &&
        this.goods.type) {
        return true
      } else {
        return false
      }
    },
    handleAddFeature () {
      if (!this.featureTxt) return
      if (this.featureTxt.length > 5) {
        this.$toast('特征词语超过5个字了～')
        return
      }
      if (this.goods.feature.indexOf(this.featureTxt) > -1) {
        this.$toast('请勿重复添加商品特征')
        return
      }
      if (this.goods.feature.length > 5) {
        this.$toast('商品特征最多5个')
        this.featureTxt = ''
        return
      }
      this.goods.feature.push(this.featureTxt)
      this.featureTxt = ''
    },
    handleDelFeature (item) {
      let index = this.goods.feature.indexOf(item)
      this.goods.feature.splice(index, 1)
    },
    beforeRead (file) {
      let repeatImg = this.goods.uploadImgs.find(d => d.file.name === file.name)
      if (repeatImg) {
        this.$toast('已经选择过当前图片了')
        return false
      } else {
        return true
      }
    }
  },
  computed: {
    ...mapState(['user']),
    hasUpdated () {
      return this.isEdit
    }
  },
  watch: {
    'goods.discountsType' () {
      this.goods.discounts = ''
    },
    'goods.title' (val) {
      this.rule.title = val.length > 40 ? '商品标题超过40个字' : ''
    },
    'goods.desc' (val) {
      this.rule.desc = val.length > 150 ? '商品描述超过150个字' : ''
    },
    'goods.discounts' (val) {
      // 折扣的范围
      if (this.goods.discountsType === 1) {
        this.rule.discounts = val > 100 || val < 1 ? '折扣范围错误' : ''
      } else {
        if (this.goods.price) {
          this.rule.discounts = val > this.goods.price || val < 0 ? '优惠量不能高于商品价格' : ''
        }
      }
    },
    'goods.feature' (val) {
      this.rule.feature = val.length > 0 ? '' : '商品特征不能为空'
    },
    'goods.residue' (val) {
      this.rule.residue = `${val}`.length > 0 ? '' : '商品余量不能为空'
    },
    'goods.limit' (val) {
      this.rule.residue = `${val}`.length > 0 ? '' : '日消费限额不能为空'
    },
    'goods.unit' (val) {
      this.rule.unit = val.length > 0 ? '' : '商品单位不能为空'
    }
  }
}
</script>

<style lang="scss" scoped>
.van-nav-bar .van-icon {
  color: #fff !important;
}
.van-nav-bar__title {
  color: #fff !important;
}
.van-hairline--bottom::after {
  border: none;
}
.b-t-w-15 {
  border-top-width: 15px;
}
.b-l-r-0 {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}
.b-r-r-0 {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}
.m-l--5 {
  margin-left: -5px !important;
}
.required {
  position: relative;
  &::before {
    content: "*";
    position: absolute;
    left: 8px;
    color: #f44;
    font-size: 14px;
  }
}
.select {
  background: #fff;
  color: #494949;
  border: 1px solid #f2f2f2;
  outline: none;
}
</style>
